import { defineStore } from 'pinia'
import { constantRoutes, asyncRoutes } from '@/router'

function hasPermission(roles: [], route: any) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function filterAsyncRoutes(routes: RouterTypes, roles: []) {
  const res: RouterTypes = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  return res
}

export const usePermissionStore = defineStore('permission', {
  state: () => {
    return {
      routes: ([] as RouterTypes),
      addRoutes: ([] as RouterTypes)
    }
  },
  actions: {
    SET_ROUTES(routes: RouterTypes) {
      this.$patch(state => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
      })
    },
    generateRoutes(roles: any) {
      return new Promise(async (resolve) => {
        let accessedRoutes = []
        if (roles.includes('admin')) {
          accessedRoutes = asyncRoutes || []
        } else {
          accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
        }
        this.SET_ROUTES(accessedRoutes)
        resolve(accessedRoutes)
      })
    },
  }
})
